<template>
  <div class='container'>

    <el-card>
      <span style="color:pink;font-size:12px">by祝楼帅</span>
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-form :model="addIssueForm" :rules="addIssueFormRules" ref="addIssueFormRef" label-width="100px">
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="addIssueForm.subjectID" placeholder="请选择" style="width: 400px" @change="selectChanged">
            <el-option :label="item.label" :value="item.value" v-for="item in subjectList" :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="addIssueForm.catalogID" placeholder="请选择" style="width: 400px">
            <el-option :label="item.label" :value="item.value" v-for="item in secondList" :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="addIssueForm.enterpriseID" placeholder="请选择" style="width: 400px">
            <el-option :label="item.company" :value="item.id" v-for="item in companyList" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="province">
          <el-select v-model="addIssueForm.province" placeholder="请选择" style="width: 195px;margin-right:5px"
            @change="selectListChanged">
            <el-option :label="item" :value="item" v-for="(item,index) in provinceList" :key="index">
            </el-option>
          </el-select>
          <el-select v-model="addIssueForm.city" placeholder="请选择" style="width: 200px">
            <el-option :label="item" :value="item" v-for="(item,index) in cityList" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select v-model="addIssueForm.direction" placeholder="请选择" style="width: 400px">
            <el-option :label="item" :value="item" v-for="(item,index) in direction" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：">
          <el-radio v-model="addIssueForm.questionType" label="1" @change="changeValue">单选</el-radio>
          <el-radio v-model="addIssueForm.questionType" label="2" @change="changeValue">多选</el-radio>
          <el-radio v-model="addIssueForm.questionType" label="3" @change="changeValue">简答</el-radio>
        </el-form-item>
        <el-form-item label="难度：">
          <el-radio v-model="addIssueForm.difficulty" label="1">简单</el-radio>
          <el-radio v-model="addIssueForm.difficulty" label="2">一般</el-radio>
          <el-radio v-model="addIssueForm.difficulty" label="3">困难</el-radio>
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <quill-editor v-model="addIssueForm.question" :options="editorOption" ref="myQuillEditor"
            @blur="onEditorBlur($event)">
          </quill-editor>
        </el-form-item>

        <el-form-item label="选项：" v-if="addIssueForm.questionType==='1'">
          <div style="margin-bottom:15px" v-for="(item,index) in addIssueForm.options" :key="index">
            <el-radio v-model="tabradio" @change="getValue" :label="item.code" style="margin-right:0px">
              {{item.code}}：</el-radio>
            <el-input v-model="item.title" style="width: 200px"></el-input>
            <div class="div_upload">
              <el-upload class="avatar-uploader" :on-success="(res,file)=>{handleAvatarSuccess(item.code,res,file)}"
                :before-upload="beforeAvatarUpload" action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false">
                <img v-if="imgExist(item.code)" :src="imgUrl(item.code)" class="avatar">
                <span v-else>上传图片</span>
              </el-upload>
              <i class="el-icon-circle-close"></i>
            </div>
          </div>
          <el-button type="danger" :disabled="true" size="mini">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="选项：" v-if="addIssueForm.questionType==='2'">
          <div style="margin-bottom:15px" v-for="(item,index) in addIssueForm.options" :key="index">
            <!-- <el-radio v-model="tabradio" :label="item" style="margin-right:0px">{{item}}：</el-radio> -->
            <el-checkbox v-model="addIssueForm.options[index].isRight"
              @change="checked=>checkchange(checked, item.code)">
              {{item.code}}：
            </el-checkbox>
            <el-input v-model="item.title" style="width: 200px"></el-input>
            <div class="div_upload">
              <el-upload class="avatar-uploader" :on-success="(res,file)=>{handleAvatarSuccess(item.code,res,file)}"
                :before-upload="beforeAvatarUpload" action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false">
                <img v-if="imgExist(item.code)" :src="imgUrl(item.code)" class="avatar">
                <span v-else>上传图片</span>
              </el-upload>
              <i class="el-icon-circle-close"></i>
            </div>
          </div>
          <el-button type="danger" :disabled="false" size="mini" @click="addOptions">+增加选项与答案</el-button>
        </el-form-item>

        <el-form-item label="解析视频：">
          <el-input v-model="addIssueForm.videoURL" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="答案解析：" prop="answer">
          <quill-editor v-model="addIssueForm.answer" :options="editorOption" @blur="onEditorBlur1($event)">
          </quill-editor>
        </el-form-item>

        <el-form-item label="题目备注：">
          <el-input type="textarea" v-model="addIssueForm.remarks" style="width: 400px"></el-input>
        </el-form-item>

        <el-form-item label="试题标签：">
          <el-select v-model="addIssueForm.tags" multiple placeholder="请选择试题标签" style="width: 400px"
            @change="selectTagsChanged">
            <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认提交</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import { direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys.js'
export default {
  data () {
    return {
      addIssueForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        // 难度
        difficulty: '1',
        // 题型
        questionType: '1',
        // 提交时是字符串
        tags: [],
        options: [{
          isRight: false,
          code: 'A',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'B',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'C',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'D',
          title: '',
          img: ''
        }]
      },
      addIssueFormRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请选择答案解析', trigger: 'blur' }
        ]
      },
      tabradio: null,
      title: '',
      imgList: [
        // {
        //   imageUrl: null
        // }
      ],
      checkList: [false, false, false, false],
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block', 'image', 'link']
          ]
        }
      },
      content: '',
      // 学科列表
      subjectList: [],
      // 目录列表
      secondList: [],
      // 试题标签列表
      tagsList: [],
      // 企业列表
      companyList: [],
      provinceList: [],
      cityList: [],
      direction,
      tabList2: ['A', 'B', 'C', 'D'],
      checked1: false
    }
  },
  methods: {
    changeValue (event) {
      if (this.addIssueForm.questionType === '1') {
        this.addIssueForm.options = [{
          isRight: false,
          code: 'A',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'B',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'C',
          title: '',
          img: ''
        }, {
          isRight: false,
          code: 'D',
          title: '',
          img: ''
        }]
      }
    },
    getValue (val) {
      const i = this.addIssueForm.options.findIndex(item => item.code === this.tabradio)
      this.addIssueForm.options.forEach(item => {
        item.isRight = false
      })
      this.addIssueForm.options[i].isRight = true
    },
    onEditorBlur (quill) {
      if (this.addIssueForm.question.length === 0) {
        this.$refs.addIssueFormRef.validateField('question')
      } else {
        this.$refs.addIssueFormRef.validateField('question')
      }
    },
    onEditorBlur1 (quill) {
      if (this.addIssueForm.answer.length === 0) {
        this.$refs.addIssueFormRef.validateField('answer')
      } else {
        this.$refs.addIssueFormRef.validateField('answer')
      }
    },
    addOptions () {
      const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
      if (this.addIssueForm.options.length >= arr.length) {
        this.$message.error('不能再增加选项了')
      } else {
        this.addIssueForm.options.push({
          isRight: false,
          code: arr[this.addIssueForm.options.length],
          title: '',
          img: ''
        })
      }
    },
    checkchange (val, code) {
      const i = this.addIssueForm.options.findIndex(item => item.code === code)
      this.addIssueForm.options[i].isRight = val
    },
    onSubmit () {
      this.$refs.addIssueFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        } else {
          const addIssueFormObj = JSON.parse(JSON.stringify(this.addIssueForm))
          addIssueFormObj.tags = addIssueFormObj.tags.join(',')
          if (this.$route.query.id) {
            await this.$store.dispatch('updateQuestion', addIssueFormObj)
          } else {
            await this.$store.dispatch('addQuestion', addIssueFormObj)
          }
          this.$router.push('list')
        }
      })
    },
    imgExist (code) {
      const i = this.addIssueForm.options.findIndex(item => item.code === code)
      let flag = false
      if (this.addIssueForm.options[i].img.length === 0) {
        flag = false
      } else {
        flag = true
      }
      return flag
    },
    imgUrl (code) {
      const i = this.addIssueForm.options.findIndex(item => item.code === code)
      return i === -1 ? '' : this.addIssueForm.options[i].img
    },
    handleAvatarSuccess (code, res, file) {
      const i = this.addIssueForm.options.findIndex(item => item.code === code)
      this.addIssueForm.options[i].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    handlePreview (file) {
      console.log(file)
    },
    selectListChanged (value) {
      this.addIssueForm.city = ''
      this.cityList = citys(value)
    },
    async getSubjectList () {
      const { data: res } = await this.$store.dispatch('getSimpleList')
      this.subjectList = res
    },
    async getCompanyList () {
      const { data: res } = await this.$store.dispatch('getCompanyList', 10000)
      this.companyList = res.items
    },
    async selectChanged (value) {
      const { data: res1 } = await this.$store.dispatch('getSecondList', value)
      const { data: res2 } = await this.$store.dispatch('getTagsList', value)
      this.secondList = res1
      this.tagsList = res2
    },
    async selectTagsChanged (value) {
      // console.log(this.addIssueForm)
    },
    async getDetailList (id, subjectID) {
      const { data: res } = await this.$store.dispatch('getPreviewObj', id)
      const { data: res1 } = await this.$store.dispatch('getSecondList', subjectID)
      const { data: res2 } = await this.$store.dispatch('getTagsList', subjectID)
      res.tags = res.tags.split(',')
      if (res.questionType === '1') {
        res.options.forEach(item => {
          if (item.isRight === 1) {
            this.tabradio = item.code
          }
        })
      }
      if (res.questionType === '2') {
        res.options.forEach(item => {
          if (item.isRight === 0) {
            item.isRight = false
          } else {
            item.isRight = true
          }
        })
      }
      this.addIssueForm = res
      this.secondList = res1
      this.tagsList = res2
    }
  },
  created () {
    if (this.$route.query.id) {
      this.getDetailList(this.$route.query.id, this.$route.query.subjectID)
    } else {

    }
    this.getSubjectList()
    this.getCompanyList()
    this.provinceList = provinces()
  },
  updated () {
    // 回到顶部
    // document.body.scrollTop = document.documentElement.scrollTop = 0
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 15px;
}
/deep/ .ql-editor {
  height: 200px;
}
.div_upload {
  position: relative;
  display: inline-block;
  text-align: center;
  border: 1px dashed #ccc;
  //padding: 10px;
  color: black;
  background-color: #fff;
  margin-left: 5px;
  border-radius: 5px;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
// .avatar-uploader {
//   text-align: center;
//   border: 1px dashed #ccc;
//   padding: 10px;
//   color: black;
//   background-color: #fff;
//   margin-left: 5px;
//   border-radius: 5px;
//   width: 100px;
// }
.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 60px;
}
</style>
